package com.atguigu.gmall.payment.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.GmallException;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.payment.bean.PaymentInfoEntity;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.feign.OmsClient;
import com.atguigu.gmall.payment.mapper.PaymentMapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping
@Slf4j
public class AlipayController {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OmsClient omsClient;
    @Autowired
    PaymentMapper paymentMapper;
    @ApiOperation("获取支付二维码")
    @GetMapping("alipay.html")
    @ResponseBody
    public String alipayNative(@RequestParam("orderToken") String orderToken){
        ResponseVo<OrderEntity> orderEntityResponseVo = omsClient.queryOrderByOrderToken(orderToken);
        OrderEntity orderEntity = orderEntityResponseVo.getData();
        if(orderEntity==null){
            throw new GmallException("没有此订单,请联系管理员");
        }
        if(orderEntity.getStatus()!=0){
            throw new GmallException("订单状态异常,请联系管理员");
        }
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.gatewayUrl, //要访问的支付宝平台的网关地址
                AlipayConfig.app_id, //我们的应用注册到支付宝的应用id
                AlipayConfig.merchant_private_key, //我们的私钥：发送数据给支付宝时加密使用
                "json", //数据传递的格式
                AlipayConfig.charset, // 字符编码
                AlipayConfig.alipay_public_key, //应用注册时支付宝分配的公钥
                AlipayConfig.sign_type); // 秘钥生成的方式
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //同步回调接口地址
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        //异步回调接口地址
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //根据orderToken查询订单信息
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderToken;
        //付款金额，必填
        //订单总金额，单位为元，精确到小数点后两位
        String total_amount = "0.01";//orderEntity.getPayAmount().doubleValue()+"";
        //订单名称，必填  支付宝扫码时显示的商品信息
        String subject = "谷粒手机";
        //商品描述，可空
//        String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
            //result是一个自动提交的表单页面的字符串，该表单页面中的js脚本会自动提交请求获取支付二维码展示
            return result;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new GmallException("生成支付二维码失败,请联系管理员");
        }

    }
    /*
    用户支付成功后，支付宝会让浏览器重定向访问：
    http://192.168.1.1/alipay.trade.page.pay-JAVA-UTF-8/return_url.jsp?charset=utf-8&out_trade_no=202210051121441061577499248868577281&method=alipay.trade.page.pay.return&total_amount=0.01&sign=T7vSmDUvcFRSjaS%2BRQwJval17wSMtnz%2Bv1B%2BDPIwB%2Bk211M6rsIEoRGp5quCyaNAjDIO7bSkyTclKZwklp%2FGQaty1YWHHk3MrqIdFRkFIIlW%2BPlwNiJIT0ITTduAqHdUjFJ3MK2TrSOgMrxiDpTkDlzJ3mKCgrN9ghMvSvND7%2BgsOLXd%2BvP43%2B%2BsowSS%2F%2FkWG7CDhWkGLrKxsgLYV43CpcLMS1%2FlM51WqdrlHOXbz4z768ntX0PS%2BxRQWgfIJ3bZERm7HCQPE5z2PJJkjyP01j%2BKOrA%2BctgiWjfW42UoBtZkCQzFrxnZ7mYmYrosDtNgDfbCQux7Fn28b%2FWQTnl4OQ%3D%3D&trade_no=2022100522001432271453596133&auth_app_id=2021001163617452&version=1.0&app_id=2021001163617452&sign_type=RSA2&seller_id=2088831489324244&timestamp=2022-10-05+11%3A22%3A29
        访问的是returnurl 同步通知的接口地址
        同时将用户支付的结果以请求参数的形式交给接口

   */
    //同步回调接口:  http://payment.gmall.com/returnUrl
    @GetMapping("returnUrl")
    public String returnUrl(HttpServletRequest request) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        //获取支付宝返回的支付信息数据
        Map<String,String[]> requestParams = request.getParameterMap();
        //获取所有key唯一的值
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //params:代表用户支付的所有的信息
        //验证数据的签名是否正确
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        log.info("支付宝回调通知参数：{}" , params);
        if(signVerified) {//验证签名通过
            //商户订单号
            String out_trade_no = params.get("out_trade_no");
            //用户实际支付的金额
            String total_amount = params.get("total_amount");
            //判断用户支付金额是否和订单应付金额一致
            ResponseVo<OrderEntity> orderEntityResponseVo = omsClient.queryOrderByOrderToken(out_trade_no);
            OrderEntity orderEntity = orderEntityResponseVo.getData();
            if(orderEntity!=null &&
                    new BigDecimal("0.01").compareTo(new BigDecimal(total_amount))==0){
                //支付成功：响应成功页面
                return "paysuccess";
            }

        }
        //支付失败：跳转到支付失败的页面
        throw new GmallException("支付失败");
    }
    @ApiOperation("异步通知支付结果")
    @ResponseBody
    @PostMapping("alipay/notifyUrl")//http://ls074ejc73x7.ngrok.xiaomiqiu123.top/alipay/notifyUrl
    public String notifyUrl(HttpServletRequest request) throws Exception {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key,
                AlipayConfig.charset,
                AlipayConfig.sign_type); //调用SDK验证签名
	/* 实际验证过程建议商户务必添加以下校验：
        1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
	*/
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = params.get("out_trade_no");
            String totalAmount = params.get("total_amount");
            //验证支付金额
            ResponseVo<OrderEntity> orderEntityResponseVo = omsClient.queryOrderByOrderToken(out_trade_no);
            OrderEntity orderEntity = orderEntityResponseVo.getData();
            if(orderEntity==null||
             orderEntity.getStatus()!=0||
             !"0.01".equals(totalAmount)){
                log.info("异步回调失败：{} "+ JSON.toJSONString(params));
                return "failure";
            }
            //支付宝交易号
            String trade_no = params.get("trade_no");

            //交易状态
            String trade_status = params.get("trade_status");
            //TRADE_SUCCESS代表用户支付成功
            if(trade_status.equals("TRADE_SUCCESS")){
                //修改订单状态：orderToken：更新订单的状态为已支付
                //更新库存销量：orderToken可以获取到该订单锁定的库存数据  修改库存  锁定库存  销量
                //发送订单支付成功的消息：
                rabbitTemplate.convertAndSend("pay.exchange"
                    ,"pay.success" ,out_trade_no );
                //更新用户积分： 使用订单对象的用户id  账户加积分
                Map<String,Object> map = new HashMap<>();
                map.put("userId" , orderEntity.getUserId());
                map.put("growth" , orderEntity.getGrowth());
                map.put("integration" , orderEntity.getIntegration());
                rabbitTemplate.convertAndSend("pay.exchange"
                        ,"pay.user.jifen" , map);
                //保存支付日志： 自己保存   以后对账使用
                PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
                BeanUtils.copyProperties(params, paymentInfo);
                String gmtCreate = params.get("gmt_create");
                Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(gmtCreate);
                paymentInfo.setCreateTime(date);
                paymentInfo.setCallbackTime(new Date());
                paymentInfo.setCallbackContent(JSON.toJSONString(params));
                paymentMapper.insert(paymentInfo);
                System.out.println("订单支付成功:"+JSON.toJSONString(params));
                return "SUCCESS";
            }
        }
        //交易失败
        return "failure";
    }
}
